package com.hot100;

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

public class Solution105 {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return build(preorder, inorder, 0, preorder.length - 1, 0, inorder.length - 1);
    }

    public TreeNode build(int[] preorder, int[] inorder, int preStart, int preEnd, int inStart, int inEnd) {
        if (preStart > preEnd) return null;
        if (preStart == preEnd) return new TreeNode(preorder[preStart]);
        TreeNode root = new TreeNode(preorder[preStart]);
        int index = find(inorder, inStart, inEnd, root.val);
        root.left = build(preorder, inorder, preStart + 1, preStart + index - inStart, inStart, index - 1);
        root.right = build(preorder, inorder, preStart + index - inStart + 1, preEnd, index + 1, inEnd);
        return root;
    }

    public int find(int[] nums, int i, int j, int target) {
        for (int k = i; k <= j; k++) {
            if (nums[k] == target) return k;
        }
        return -1;
    }


}
